<?php


namespace PKApp\Topic\Classes;


use PKFrame\DataHandler\Arrays;
use PKFrame\Service;

class TopicService extends Service
{

    private $_sitePath;

    public function interface_getEntityById($id, $viewField = '*')
    {
        return $this->getEntityById($id, 'Empty_TopicId', 'Empty_Topic', $viewField);
    }

    protected function db(): TopicDB
    {
        static $cls;
        !empty($cls) ?: $cls = new TopicDB();
        return $cls;
    }

    public function Count($viewParams = []): int
    {
        array_key_exists('isDeleted', $viewParams) ?: $viewParams['isDeleted'] = 0;
        return $this->db()->Where($viewParams)->Count();
    }

    public function GetList($viewParams = [], $viewField = '*')
    {
        array_key_exists('isDeleted', $viewParams) ?: $viewParams['isDeleted'] = 0;
        $list = $this->db()->Where($viewParams)->OrderBy('id')
            ->Select($viewField)->ToList();
        if (Arrays::Is($list)) {
            foreach ($list as $index => $item) {
                $item['url'] = (empty($this->_sitePath) ? '' : $this->_sitePath) . '/' . str_replace('[id]', $item['id'], $item['fileHtml']);
                $list[$index] = $item;
            }
        }
        return $list;
    }

    public function GetEntity($viewParams = [], $viewField = '*')
    {
        array_key_exists('isDeleted', $viewParams) ?: $viewParams['isDeleted'] = 0;
        return $this->db()->Where($viewParams)->Select($viewField)->First();
    }

    /**
     * @param mixed $sitePath
     */
    public function SetSitePath($sitePath): void
    {
        $this->_sitePath = $sitePath;
    }
}